const User = require('../models/User');
const jwt = require('jsonwebtoken');
const LoginLog = require('../models/LoginLog');

// 生成 JWT Token
const generateToken = (id) => {
  return jwt.sign({ id }, process.env.JWT_SECRET, {
    expiresIn: '30d'
  });
};
// 记录登录日志
const logLoginAttempt = async (user, status, req) => {
  try {
    await LoginLog.create({
      user: user._id,
      status,
      ip: req.ip
    });
  } catch (error) {
    console.error('Failed to create login log:', error);
  }
};

// 注册新用户
const register = async (req, res) => {
  try {
    const { username, email, password } = req.body;

    // 检查用户是否已存在
    const userExists = await User.findOne({ $or: [{ email }, { username }] });
    if (userExists) {
      return res.status(400).json({ 
        code: 400,
        message: '用户已存在',
        data: null
      });
    }
    
    // 创建新用户
    const user = await User.create({
      username,
      email,
      password
    });

    // 生成 token
    const token = generateToken(user._id);

    res.status(201).json({
      code: 200,
      data: {
        token
      },
      message: 'success'
    });
  } catch (error) {
    res.status(500).json({ 
      code: 500,
      message: error.message,
      data: null
    });
  }
};

// 用户登录
const login = async (req, res) => {
  try {
    const { email, password } = req.body;

    // 查找用户
    const user = await User.findOne({ email });

    if (!user) {
      await logLoginAttempt(user, 'failed', req);
      return res.status(401).json({ 
        code: 401,
        message: '邮箱或密码错误',
        data: null
      });
    }

    // 验证密码
    const isMatch = await user.matchPassword(password);
    if (!isMatch) {
      await logLoginAttempt(user, 'failed', req);
      return res.status(401).json({ 
        code: 401,
        message: '邮箱或密码错误',
        data: null
      });
    }

    // 记录成功登录
    await logLoginAttempt(user, 'success', req);

    // 生成 token
    const token = generateToken(user._id);

    res.json({
      code: 200,
      data: {
        token
      },
      message: 'success'
    });
  } catch (error) {
    res.status(500).json({ 
      code: 500,
      message: error.message,
      data: null
    });
  }
};

// 获取当前用户信息
const getMe = async (req, res) => {
  try {
    const user = await User.findById(req.user._id).select('-password');
    res.json({
      code: 200,
      data: user,
      message: 'success'
    });
  } catch (error) {
    res.status(500).json({ 
      code: 500,
      message: error.message,
      data: null
    });
  }
};

// 获取用户登录历史
const getLoginHistory = async (req, res) => {
  try {
    const loginLogs = await LoginLog.find({ user: req.user._id })
      .sort({ timestamp: -1 })
      .limit(10)
      .populate('user', 'username email')
      .lean();
      
    res.json({
      code: 200,
      data: loginLogs,
      message: 'success'
    });
  } catch (error) {
    res.status(500).json({ 
      code: 500,
      message: error.message,
      data: null
    });
  }
};

module.exports = {
  register,
  login,
  getMe,
  getLoginHistory
};